package org.csu.canteen.controller;

import jakarta.servlet.http.HttpSession;
import org.csu.canteen.entity.*;
import org.csu.canteen.service.*;
import org.csu.canteen.service.Impl.AccountServiceImpl;
import org.csu.canteen.vo.AccountVO;
import org.csu.canteen.vo.ProductVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/order")

public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private CartItemService cartItemService;
    // 获取用户登录信息
    @Autowired
    private AccountService accountService;

    @Autowired
    private CatalogService catalogService;
    @Autowired
    private ItemService itemService;

    public OrderController( CartItemService cartItemService, CouponService couponService) {

    }
    @GetMapping("/confirmOrderForm")
    public String showConfirmOrderForm(@RequestParam("orderId") Long orderId, Model model) {
        Orders order = orderService.getOrderById(Math.toIntExact(orderId));
        if (order == null) {
            return "redirect:/order/newOrder";
        }
        model.addAttribute("order", order);
        model.addAttribute("orderDate", new Date());
        return "order/confirmOrder";
    }

    @GetMapping("/listOrders")
    public String showOrderList(@RequestParam("username") String username, Model model) {
        List<Orders> orderList = orderService.getOrdersByUsername(username);
        model.addAttribute("orderList", orderList);
        return "order/listOrder";
    }

    @GetMapping("/newOrder")
    public String showNewOrderForm(@RequestParam("username") String username, Model model) {
        Orders order = new Orders();
        AccountVO loginAccount = accountService.getAccountByUsername(username);
        model.addAttribute("order", order);
        model.addAttribute("username", username);
        model.addAttribute("loginAccount", loginAccount);
        return "order/newOrder";
    }

    @GetMapping("/orderTabs")
    public String showOrderTabs(@RequestParam("username") String username,HttpSession session, Model model) {
        Cart cart = (Cart) session.getAttribute("cart");
        // 2. 查询 cartitem 表，获取购物车商品列表
        List<CartItem> cartItems = cart.getCartItemList();


        // 3. 查询 item 表，把 item 关联到 cartItem
        Map<String, Item> itemMap = itemService.getItemMapByItemIds(
                cartItems.stream().map(CartItem::getItemId).collect(Collectors.toList())
        );
        for (CartItem cartItem : cartItems) {
            cartItem.setItem(itemMap.get(cartItem.getItemId()));
        }

// 4. 查询 product 表，把 product 关联到 item
        Map<String, ProductVO> productVOMap = catalogService.getAllProducts().stream()
                .collect(Collectors.toMap(ProductVO::getProductId, Function.identity()));

        for (Item item : itemMap.values()) {
            item.setProductVO(productVOMap.get(item.getProductId())); // 假设 Item 有 setProduct 方法
        }

        BigDecimal subTotal = cartItems.stream()
                .filter(item -> item.getItem() != null) // 确保 item 不是 null
                .map(item -> item.getItem().getListPrice().multiply(BigDecimal.valueOf(item.getQuantity()))) // 单价 * 数量
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        Orders order = new Orders(); // 创建订单对象
        model.addAttribute("products", productVOMap);
        model.addAttribute("cart", cartItems);
        model.addAttribute("order", order);
        model.addAttribute("subtotal", subTotal);
        model.addAttribute("username", username);
        return "order/orderTabs";
    }

    @PostMapping("/submitOrder")
    public String submitOrder(@ModelAttribute Orders order,
                              @RequestParam("username") String username,HttpSession session, RedirectAttributes redirectAttributes) {
        Cart cart = (Cart) session.getAttribute("cart");
        // 2. 查询 cartitem 表，获取购物车商品列表
        List<CartItem> cartItems = cart.getCartItemList();
        if (cartItems == null) {
            return "redirect:/cart/cart";
        }
        AccountVO loginAccount = accountService.getAccountByUsername(username);
        // 3. 查询 item 表，把 item 关联到 cartItem
        Map<String, Item> itemMap = itemService.getItemMapByItemIds(
                cartItems.stream().map(CartItem::getItemId).collect(Collectors.toList())
        );
        for (CartItem cartItem : cartItems) {
            cartItem.setItem(itemMap.get(cartItem.getItemId()));
        }
        order.initOrder(loginAccount, cartItems);
        orderService.insertOrder(order);
        redirectAttributes.addFlashAttribute("message", "Order submitted successfully!");
        return "redirect:/order/success";
    }

    @GetMapping("/success")
    public String orderSuccess(HttpSession session) {
        AccountVO loginAccount = (AccountVO) session.getAttribute("loginAccount");
        String username = loginAccount.getUsername();
        return "redirect:/common/countDownToOrder?username=" + username;
    }

    @GetMapping("/shippingForm")
    public String showShippingForm(Model model) {
        model.addAttribute("order", new Orders());
        return "order/shippingForm";
    }

    @PostMapping("/mainForm")
    public String processShippingForm(@ModelAttribute Orders order) {
        return "redirect:/order/orderTabs";
    }

    @GetMapping("/viewOrder")
    public String viewOrder(@RequestParam("orderId") Long orderId, Model model) {
        Orders order = orderService.getOrderById(Math.toIntExact(orderId));
        if (order == null) {
            return "redirect:/order/mainForm";
        }
        model.addAttribute("order", order);
        return "order/viewOrder";
    }
}